from kubernetes import client, config
from kubernetes.client.rest import ApiException

def update_configmap(namespace, name, data):
    """
    更新指定 namespace 下的 ConfigMap 的 data 字段
    :param namespace: 命名空间
    :param name: ConfigMap 名称
    :param data: dict 格式，key 是文件名，value 是内容字符串
    """
    # 加载 kubeconfig 配置（集群外）或者集群内环境自动加载
    try:
        config.load_kube_config(config_file="/etc/rancher/k3s/k3s.yaml")  # 如果脚本运行在集群外用这个
    except:
        config.load_incluster_config()  # 集群内执行

    v1 = client.CoreV1Api()

    try:
        # 先读取当前 ConfigMap
        cm = v1.read_namespaced_config_map(name, namespace)
        # 更新 data
        cm.data = data
        # 发送更新请求
        v1.replace_namespaced_config_map(name, namespace, cm)
        print(f"ConfigMap '{name}' 在命名空间 '{namespace}' 更新成功。")
    except ApiException as e:
        print(f"更新 ConfigMap 失败: {e}")

if __name__ == "__main__":
    namespace = "default"
    cm_name = "nginx-config"
    new_data = {
        "default.conf": """
proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=my_cache:10m max_size=1g inactive=60m use_temp_path=off;

server {
    listen 443 ssl;
    server_name dns.glofcdn.com;

    ssl_certificate /etc/letsencrypt/live/tls.crt;
    ssl_certificate_key /etc/letsencrypt/live/tls.key;

    location / {
        proxy_cache my_cache;
        proxy_cache_valid 200 302 10m;
        proxy_cache_valid 404 1m;
        proxy_ignore_headers Cache-Control;

        proxy_pass http://catpd.cn;
        proxy_set_header Host $host;

        add_header X-Cache-Status $upstream_cache_status;
        add_header X-Pod-Name $hostname;
    }
}
"""
    }

    update_configmap(namespace, cm_name, new_data)

